<?php 
/**
 * Created by Sublime
 * User: yinni
 * Date: 2017/10/07
 * Time: 16:53
 */
namespace App\Services\Admin;

use Facades\App\Repositories\Eloquent\CoringRepositoryEloquent;
use Facades\App\Repositories\Eloquent\UserRepositoryEloquent;
use Facades\App\Repositories\Eloquent\MonitorRepositoryEloquent;
use Facades\App\Repositories\Eloquent\Monitor_alarmRepositoryEloquent;
use Facades\App\Repositories\Eloquent\Monitor_alarm_historyRepositoryEloquent;
use Facades\App\Repositories\Eloquent\Room_loopRepositoryEloquent;
use Facades\Yajra\Datatables\Html\Builder;
use App\Traits\DatatableActionButtonTrait;
use App\Http\Controllers\MailController;
use Datatables;
use Exception;
use DB;

class MonitordefineService{
	use DatatableActionButtonTrait;

	protected $module = 'monitordefine'; //模块路由

	protected $indexRoute = 'monitordefine.index'; 

	protected $createRoute = 'monitordefine.create';

	protected $showRoute = 'monitordefine.show';

	protected $editRoute = 'monitordefine.edit';

	protected $destroyRoute = 'monitordefine.destroy';

    public function __construct() {
        // 定义当前需使用的数据表
        $this->coring = CoringRepositoryEloquent::all();
        $this->monitor = MonitorRepositoryEloquent::all();
        $this->monitor_alarm = Monitor_alarmRepositoryEloquent::all();
        $this->monitor_alarm_history = Monitor_alarm_historyRepositoryEloquent::all();
        $this->room_loop = Room_loopRepositoryEloquent::all();
        $this->send_mail = new MailController();
    }


	/**
	 * 首页
	 * @return array
	 */
	public function index() {
		if(request()->ajax()) {
			return $this->ajaxData();
		}
        $html = Builder::parameters([
            'searchDelay' => 350,
            'language' => [
                'url' => url(getThemeAssets('dataTables/language/zh.json', true))
            ],
            'drawCallback' => <<<Eof
					function() {
				        LaravelDataTables["dataTableBuilder"].$('.tooltips').tooltip( {
				          placement : 'top',
				          html : true
				        });
			        },
Eof
        ])->addIndex(['data' => 'DT_Row_Index', 'name' => 'DT_Row_Index', 'title' => trans('common.number')])
            ->addColumn(['data' => 'monitor_id', 'name' => 'monitor_id', 'title' => trans('alarmsetting.monitor_id')])
            ->addColumn(['data' => 'loop_name', 'name' => 'loop_name', 'title' => trans('alarmsetting.loop_name')])
            ->addAction(['data' => 'action', 'name' => 'action', 'title' => trans('common.action')]);

            return compact('html');
        }

    /**
     * datatable数据,核心逻辑处理
     * @return mixed
     */
    public function ajaxData() {
        return Datatables::of(MonitorRepositoryEloquent::all())
            ->addIndexColumn()
            ->addColumn('action', function ($permission)
            {
                return $this->getActionButtonAttribute($permission->monitor_id);
            })
            ->make(true);        
    }

    /**
     * 实时监测json数据
     * @return json
     */
    public function ajaxJsonData() {
        return CoringRepositoryEloquent::all();
    }

    /**
     * 重写datatable action按钮
     * @param $id
     * @return string
     */
    public function getActionButtonAttribute($id)
    {
        return $this->getShowActionButtion($id).
            $this->getEditActionButton($id).
            $this->getDestroyActionButton($id);
    }

    /**
     * 查看
     * @param $id
     * @return array|\Illuminate\Http\RedirectResponse
     */
    public function show($id)
    {
        // try {
        //     $user = UserRepositoryEloquent::with(['userPermissions', 'roles'])->find(decodeId($id, $this->module));
        //     $permissions = $this->getAllPermissions();
        //     $roles = $this->getAllRole();
        //     return compact('user', 'permissions', 'roles');
        // } catch (Exception $e) {
        //     flash(trans('common.find_error'), 'danger');
        //     return redirect()->route($this->indexRoute);
        // }
    }

    /**
     * 修改测点信息
     * @param $monitor_id
     * @return array|\Illuminate\Http\RedirectResponse
     */
    public function edit($monitor_id)
    {
        try {
            // dump(decodeId($monitor_id));die;
            // dump($this->module);die;
            // $monitor = MonitorRepositoryEloquent::all()->find(decodeId($monitor_id, $this->module));
            $monitor_id = decodeId($monitor_id);
            $monitor = $this->monitor->where('monitor_id',$monitor_id)->first();
            // $permissions = $this->getAllPermissions();
            // $roles = $this->getAllRole();
            // dump($monitor);die;
            return compact('monitor');
        } catch (Exception $e) {
            flash(trans('common.find_error'), 'danger');
            return redirect()->route($this->indexRoute);
        }
    }

    /**
     * 修改数据
     * @param $attributes
     * @param $id
     * @return string
     */
    public function update($attribute,$id) {
        // dump($attribute);die;
        // try{
            if (isset($attribute['monitor_id'])) {
                $result = DB::table('monitor')->where('monitor_id',$attribute['monitor_id'])
                                      ->update(['monitor_id' => $attribute['monitor_id'],
                                                'loop_name' => $attribute['loop_name']
                                            ]);
                // dump($result);die;
                if ($result) {
                    // 
                // cacheClear();
                }
                flash_info($result,trans('common.edit_success'),trans('common.edit_error'));
                return $this->indexRoute;
            }
        // }catch(Exception $e){
        //     flash(trans('common.edit_error'),'danger');
        //     return $this->indexRoute;
        // }

    } 
}